package com.husd.framework.nio;

import com.google.common.primitives.Ints;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.StandardCharsets;

/**
 * @author hushengdong@gome.com.cn
 * @date 2022/1/22 11:37 上午
 */
public class BasicChannelExample {

    public static void main(String[] args) throws IOException {

       String f = "/tmp/nio-data.txt";

       write2File(f);
       readFromFile(f);
    }

    private static void write2File(String file) throws IOException {

        //nio 的基本用法
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
        FileChannel inChannel = randomAccessFile.getChannel();
        inChannel.position(inChannel.size());

        // System.out.println(inChannel.size());

        // read from buffer into channel.
        byte[] intBytes = "10".getBytes(StandardCharsets.UTF_8);
        byte[] intBytes2 = Ints.toByteArray(10);
        System.out.println(intBytes.equals(intBytes2));
        ByteBuffer intBuffer = ByteBuffer.allocate(512);
        System.out.println(intBuffer.order().toString());
        //intBuffer.order(ByteOrder.BIG_ENDIAN);
        intBuffer.clear();
        intBuffer.put(intBytes2);
        intBuffer.flip();

        // write data from buffer 2 channel
        long bytesWritten = 0L;
        while(intBuffer.hasRemaining()) {
            bytesWritten += inChannel.write(intBuffer);
        }
        System.out.println("写入数量：" + bytesWritten);
        inChannel.force(false);
        inChannel.close();

        randomAccessFile.close();
    }

    private static void readFromFile(String file) throws IOException {

        //nio 的基本用法
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
        FileChannel inChannel = randomAccessFile.getChannel();
        ByteBuffer buf = ByteBuffer.allocate(48);
        buf.clear();
        int bytesRead = inChannel.read(buf); // 从channel中读取数据
        CharsetDecoder charsetDecoder = Charset.forName("utf-8").newDecoder();
        while (bytesRead != -1) {
            buf.flip(); //notice this
            while (buf.hasRemaining()) {
                //System.out.print(charsetDecoder.decode(buf));
                System.out.println(buf.getInt());
            }
            buf.clear(); //记得要自己清理
            bytesRead = inChannel.read(buf);
        }
        randomAccessFile.close();
    }
}
